﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using SpotOffer.AppConstants;
using SpotOffer.CustomViews;
using SpotOffer.DataModels;
using SpotOffer.Resource;
using SpotOffer.Utils;
using SpotOffer.View;
using SpotOffer.ViewModels;
using Xamarin;
using Xamarin.Forms;
using XLabs.Forms.Controls;
using XLabs.Ioc;
using XLabs.Platform.Device;

namespace SpotOffer.View
{
    public class DealListPage : BasePage
    {
        private const int PriceLabelHeight = 30,
            LabelDescriptionHeight = 57,
            ProviderHeight = 20,
            Rowheight = 360,
            ItemMargin = 20,
            ItemPadding = 10;

        private double allocatedWidth;

        private ListView _dealListView;
        private IDevice device;
        private IDisplay display;

        public DealListPage()
        {
            _dealListView = new ListView
            {
                SeparatorVisibility = SeparatorVisibility.Default,
                BackgroundColor = AppColors.LighterGrey,
                SeparatorColor = AppColors.Grey
            };
            _dealListView.SetBinding(ListView.ItemsSourceProperty, new Binding("DealListFiltered"));
            _dealListView.SetBinding(ListView.SelectedItemProperty, new Binding("SelectedDeal", BindingMode.TwoWay));
            _dealListView.ItemSelected += (sender, e) =>
            {
                if (e.SelectedItem == null)
                    return; // don't do anything if we just de-selected the row
                // do something with e.SelectedItem
                if (App.Cache.Get<string>(CacheKeys.Settings).Equals(CacheKeys.Internal))
                {
                    Navigation.PushAsync(new DealPage { BindingContext = new DealViewModel((Deal)e.SelectedItem) }, true);
                }
                else
                {
                    Device.OpenUri(new Uri(((Deal)e.SelectedItem).url));
                }
                ((ListView)sender).SelectedItem = null; // de-select the row
            };

            //  _dealListView.RowHeight = (int)(Rowheight);
            _dealListView.IsPullToRefreshEnabled = true;
            _dealListView.HasUnevenRows = false;
            _dealListView.SetBinding(ListView.RefreshCommandProperty, new Binding("LoadDealsCommand"));
            _dealListView.SetBinding(ListView.IsRefreshingProperty, new Binding("IsBusy", BindingMode.OneWay));
            // _dealListView.PropertyChanged += ScrollTo;


            var searchInput = new CustomEntry();
            searchInput.SetBinding(Entry.TextProperty, "Search");
            searchInput.TextColor = AppColors.Darkblu;
            searchInput.BackgroundColor = AppColors.White;
            searchInput.Placeholder = AppResources.Search;
            searchInput.PlaceholderTextColor = AppColors.Grey;

            // Dismiss keyboard when menu home button is touched
            // App.AppInstance.MasterPageSpotOffer.IsPresentedChanged += (sender, arg) => { searchInput.Unfocus(); };

            var separatorfirst = new Separator
            {
                Color = AppColors.Darkblu,
                //BackgroundColor = AppColors.LighterGrey,
                StrokeType = StrokeType.Dotted
            };

            var _separator = new Separator
            {
                Color = AppColors.Darkblu,
                // BackgroundColor = AppColors.LighterGrey,
                StrokeType = StrokeType.Dotted
            };

            var deleteButton = new Label
            {
                Text = AppResources.Clear,
                FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
                TextColor = AppColors.White,
                BackgroundColor = AppColors.Darkblu,
                YAlign = TextAlignment.Center,
                XAlign = TextAlignment.Center
            };
            deleteButton.SetBinding(IsVisibleProperty, "DeleteButton");

            var _tapGestureListView = new TapGestureRecognizer();
            _tapGestureListView.Tapped += (s, e) =>
            {
                searchInput.Text = "";
                searchInput.Unfocus();
            };

            deleteButton.GestureRecognizers.Add(_tapGestureListView);

            var _numberOfDeals = AppViews.OrangeLabel();

            _numberOfDeals.SetBinding(Label.TextProperty, new Binding("ResultLabel"));

            var content = new RelativeLayout();
            content.VerticalOptions = LayoutOptions.FillAndExpand;
            content.HorizontalOptions = LayoutOptions.FillAndExpand;

            content.Children.Add(separatorfirst, Constraint.Constant(0),
                Constraint.Constant(0),
                Constraint.RelativeToParent(parent => parent.Bounds.Width));

            content.Children.Add(searchInput, Constraint.Constant(0),
                Constraint.RelativeToView(separatorfirst, (parent, sibling) => sibling.Bounds.Bottom),
                Constraint.RelativeToParent(parent => parent.Width));

            content.Children.Add(_separator, Constraint.Constant(0),
                Constraint.RelativeToView(searchInput, (parent, sibling) => sibling.Height),
                Constraint.RelativeToParent(parent => parent.Bounds.Width));

            content.Children.Add(_numberOfDeals, Constraint.Constant(0),
                Constraint.RelativeToView(_separator, (parent, sibling) => sibling.Bounds.Bottom),
                Constraint.RelativeToParent(parent => parent.Bounds.Width));

            content.Children.Add(_dealListView, Constraint.Constant(0),
                Constraint.RelativeToView(_numberOfDeals, (parent, sibling) => sibling.Bounds.Bottom),
                Constraint.RelativeToParent(parent => parent.Bounds.Width),
                Constraint.RelativeToView(_numberOfDeals,
                    (parent, sibling) => parent.Bounds.Height - sibling.Bounds.Bottom));

            content.Children.Add(deleteButton,
                Constraint.RelativeToView(searchInput,
                    (parent, sibling) => sibling.Bounds.Right - deleteButton.Width - 2), Constraint.Constant(4),
                Constraint.Constant(50), Constraint.RelativeToView(searchInput, (parent, sibling) => sibling.Height - 5));
            Content = content;

            RefreshList();
        }


        protected override void OnAppearing()
        {
            base.OnAppearing();
        }

        /*    private void ScrollTo(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
            {
                var dealList = (((ListView)sender).ItemsSource);
                if (dealList == null) return;
                if (((List<Deal>)dealList).Any() & propertyChangedEventArgs.PropertyName.Equals("ItemsSource"))
                {
                    _dealListView.ScrollTo(((List<Deal>)dealList).First(), ScrollToPosition.Start, true);
                }
            }*/

        public void RefreshList()
        {
            if (App.Cache.Get<string>(CacheKeys.PictureSettings).Equals(CacheKeys.PicSmall))
            {
                _dealListView.RowHeight = 60;
                CellSmall();
            }
            else
            {
                device = Resolver.Resolve<IDevice>();
                display = device.Display;
                var ihd = display.Width;
                Debug.WriteLine("Width" + display.Width);
                var ij = display.ScreenWidthInches();
                Debug.WriteLine("ScreenWidthInches" + display.ScreenWidthInches());
                Debug.WriteLine("Xdpi" + device.Display.Xdpi);
                Debug.WriteLine("Ali Compute Width" + display.Width / device.Display.Xdpi);
                _dealListView.RowHeight = Rowheight;
                CellBigPaper();
            }
        }

        private void CellSmall()
        {
            var cell = new DataTemplate(typeof(ImageCell));

            cell.SetBinding(TextCell.TextProperty, "imagecellprice");
            cell.SetValue(TextCell.TextColorProperty, AppColors.Darkblu);
            cell.SetBinding(TextCell.DetailProperty, "title");
            cell.SetValue(TextCell.DetailColorProperty, AppColors.DarkGrey);
            cell.SetBinding(ImageCell.ImageSourceProperty, new Binding("image", converter: new NoCacheConverter()));
            cell.SetValue(BackgroundColorProperty, AppColors.White);
            _dealListView.ItemTemplate = cell;
        }

        public void CellBig()
        {
            _dealListView.ItemTemplate = new DataTemplate(() =>
            {
                var itemLayout = new AbsoluteLayout
                {
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    BackgroundColor = AppColors.LighterGrey
                };

                var imageDeal = new Image
                {
                    Aspect = Aspect.AspectFill,
                    HorizontalOptions = LayoutOptions.CenterAndExpand,
                    VerticalOptions = LayoutOptions.CenterAndExpand,

                };
                imageDeal.SetBinding(Image.SourceProperty, new Binding("image", converter: new NoCacheConverter()));


                AbsoluteLayout.SetLayoutBounds(imageDeal,
                    new Rectangle(
                        ItemMargin,
                        ItemMargin,
                        Width - ItemMargin * 2,
                        Rowheight - ItemMargin * 2));

                itemLayout.Children.Add(imageDeal);

                var gradientFront = new Image
                {
                    Aspect = Aspect.Fill,
                    Source = ImageSource.FromFile("frontgradient.png")
                };
                AbsoluteLayout.SetLayoutBounds(gradientFront,
                    new Rectangle(
                        ItemMargin,
                        ItemMargin + Rowheight / 2.5, Width - ItemMargin * 2,
                        Rowheight - Rowheight / 2.5 - ItemMargin * 2));
                itemLayout.Children.Add(gradientFront);


                var labelProvider = new ExtendedLabel
                {
                    TextColor = AppColors.White,
                    FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                    FontAttributes = FontAttributes.Bold,
                    XAlign = TextAlignment.Start,
                    YAlign = TextAlignment.End,
                    IsUnderline = true
                };
                labelProvider.SetBinding(Label.TextProperty, "provider");
                AbsoluteLayout.SetLayoutBounds(labelProvider,
                    new Rectangle(
                        ItemPadding * 2,
                        ItemPadding + Rowheight / 2.1,
                        Width - ItemMargin * 2,
                        ProviderHeight));
                itemLayout.Children.Add(labelProvider);


                var labelDealDescription = new Label
                {
                    FontSize = (Device.GetNamedSize(NamedSize.Micro, typeof(Label))) * 1.1,
                    YAlign = TextAlignment.Start,
                    XAlign = TextAlignment.Start,
                    TextColor = AppColors.White,
                    // FontAttributes = FontAttributes.Bold,
                    LineBreakMode = LineBreakMode.WordWrap
                };
                labelDealDescription.SetBinding(Label.TextProperty, "title");
                AbsoluteLayout.SetLayoutBounds(labelDealDescription,
                    new Rectangle(
                        ItemPadding * 2,
                        ItemPadding + Rowheight / 2.1 + ProviderHeight,
                        Width - ItemPadding * 4,
                        LabelDescriptionHeight));
                itemLayout.Children.Add(labelDealDescription);

                const double yPriceLabels = Rowheight - ItemMargin * 2 - PriceLabelHeight;


                var oldpricelabel = new ExtendedLabel
                {
                    TextColor = AppColors.LetterA,
                    FontSize = (Device.GetNamedSize(NamedSize.Medium, typeof(Label)) * 1.2),
                    // FontAttributes = FontAttributes.Bold,
                    YAlign = TextAlignment.End,
                    XAlign = TextAlignment.Start,
                    IsStrikeThrough = true
                    //BackgroundColor = Color.Lime
                };
                oldpricelabel.SetBinding(Label.TextProperty, "price_orig");
                AbsoluteLayout.SetLayoutBounds(oldpricelabel, new Rectangle(
                    ItemPadding * 2,
                    yPriceLabels,
                    150,
                    PriceLabelHeight));
                itemLayout.Children.Add(oldpricelabel);

                var _pricelabel = new ExtendedLabel
                {
                    TextColor = AppColors.Abacate,
                    FontSize = (Device.GetNamedSize(NamedSize.Medium, typeof(Label)) * 1.2),
                    // FontAttributes = FontAttributes.Bold,
                    YAlign = TextAlignment.End,
                    XAlign = TextAlignment.Start
                    //   IsDropShadow = false,
                    //BackgroundColor = Color.Fuchsia
                };
                _pricelabel.SetBinding(Label.TextProperty, "price");
                AbsoluteLayout.SetLayoutBounds(_pricelabel, new Rectangle(
                    ItemPadding * 3 + 100,
                    yPriceLabels,
                    120,
                    PriceLabelHeight));
                itemLayout.Children.Add(_pricelabel);

                var discountLabel = new ExtendedLabel
                {
                    TextColor = AppColors.LighterGrey,
                    FontSize = (Device.GetNamedSize(NamedSize.Medium, typeof(Label))),
                    // FontAttributes = FontAttributes.Bold,
                    YAlign = TextAlignment.End,
                    XAlign = TextAlignment.End
                    //IsStrikeThrough = true,
                    // BackgroundColor = Color.Fuchsia
                };
                discountLabel.SetBinding(Label.TextProperty, "discount");
                AbsoluteLayout.SetLayoutBounds(discountLabel, new Rectangle(
                    Width - ItemPadding * 2 - 90,
                    yPriceLabels,
                    90,
                    PriceLabelHeight));
                itemLayout.Children.Add(discountLabel);


                return new ViewCell
                {
                    View = itemLayout
                };
            });
        }

        public void CellBigPaper()
        {
            _dealListView.ItemTemplate = new DataTemplate(() =>
            {

                var itemLayout = new RelativeLayout
                {
                    HorizontalOptions = LayoutOptions.Fill,
                    VerticalOptions = LayoutOptions.Fill,
                };

                var shareButton = new Image
{
    /* Text = AppResources.ShareDeal,
     TextColor = Color.White,*/
    // BackgroundColor = Color.White,
    Source = "shareicon.png",

    Opacity = 0
};


                var gradientFront = new Label
                {
                    BackgroundColor = AppColors.White,
                };

                itemLayout.Children.Add(gradientFront, Constraint.Constant(0), Constraint.Constant(ItemMargin), Constraint.RelativeToParent((p) => (p.Bounds.Width)), Constraint.RelativeToParent((p) => (Rowheight - ItemMargin)));

                var imageDeal = new Image
                {
                    Aspect = Aspect.AspectFill,

                };
                //   imageDeal.SetBinding(Image.SourceProperty, new Binding("image_src", converter: new NoCacheConverter()));
                imageDeal.SetBinding(Image.SourceProperty, new Binding("image_src"));

                imageDeal.PropertyChanged += (sender, args) =>
                {
                    if (args.PropertyName == "IsLoading")
                    {
                        if (imageDeal.IsLoading)
                        {
                            imageDeal.Opacity = 0;
                        }
                        else
                        {
                            shareButton.FadeTo(1, 500);
                            imageDeal.FadeTo(1, 500);
                        }

                    }
                };
                itemLayout.Children.Add(imageDeal, Constraint.RelativeToParent((p) => (0)), Constraint.RelativeToParent((p) => (ItemMargin)), Constraint.RelativeToParent((p) => (p.Bounds.Width)), Constraint.RelativeToView(gradientFront, (p, s) => (Rowheight - 140 - ItemMargin)));

                var labelDealDescription = new AppViews.SpotOfferLabel
                 {
                     YAlign = TextAlignment.Start,
                     XAlign = TextAlignment.Start,
                 };
                labelDealDescription.SetBinding(Label.TextProperty, "title");
                itemLayout.Children.Add(labelDealDescription, Constraint.RelativeToView(imageDeal, (p, s) => (ItemPadding)), Constraint.RelativeToView(imageDeal, (p, s) => (s.Bounds.Bottom + ItemPadding)), Constraint.RelativeToView(imageDeal, (p, s) => (s.Bounds.Width - ItemPadding * 2)), Constraint.Constant(90));


                var _pricelabel = new AppViews.SpotOfferLabel
                 {
                     FontSize = (Device.GetNamedSize(NamedSize.Medium, typeof(Label))),
                     FontAttributes = FontAttributes.Bold,
                     YAlign = TextAlignment.End,
                     XAlign = TextAlignment.End,
                 };
                _pricelabel.SetBinding(Label.TextProperty, "price");
                itemLayout.Children.Add(_pricelabel, Constraint.Constant(ItemPadding), Constraint.Constant(Rowheight - ProviderHeight - ItemPadding));

                var oldpricelabel = new AppViews.SpotOfferLabel
                {
                    TextColor = AppColors.Grey,
                    FontSize = (Device.GetNamedSize(NamedSize.Small, typeof(Label))),
                    FontAttributes = FontAttributes.Bold,
                    YAlign = TextAlignment.End,
                    XAlign = TextAlignment.End,
                    IsStrikeThrough = true,
                };
                oldpricelabel.SetBinding(Label.TextProperty, "price_orig");
                itemLayout.Children.Add(oldpricelabel, Constraint.RelativeToView(_pricelabel, (p, s) => s.Bounds.Right + ItemPadding), Constraint.Constant(Rowheight - ProviderHeight / 1.2 - ItemPadding));

                shareButton.GestureRecognizers.Add(new TapGestureRecognizer(OnTap));

                itemLayout.Children.Add(shareButton, Constraint.RelativeToView(oldpricelabel, (p, s) => p.Bounds.Width - 60), Constraint.Constant(ItemPadding + ItemMargin), Constraint.Constant(50), Constraint.Constant(50));

                return new ViewCell
                {
                    View = itemLayout,

                };
            });
        }

        private void OnTap(Xamarin.Forms.View v, object o)
        {
            var deal = (v as Image).BindingContext as Deal;
            DependencyService.Get<IShare>().ShareStatus(deal.title + " " + deal.price + " " + deal.price_orig + " i SpotOffer(iOS AppStore - Android GooglePlay)"/*, deal.image*/);
            Insights.Track("Share", new Dictionary<string, string> { { "Share", deal.title }, });
        }


        protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);
            if (width != allocatedWidth)
            {
                allocatedWidth = width;
                _dealListView.Focus();
                //RefreshList();
            }
        }

    }
}